package struts.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 * 解析struts-config.xml文件
 * 
 * @author zhouhong
 * @date 2014-9-21 新建
 */
public class XmlConfigParse {
	public static Map<String,XmlBean> parseXml(String configPath) throws Exception, IOException{
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(configPath));
		Element root = document.getRootElement();
		Map<String,XmlBean> rmap = new HashMap<String,XmlBean>();
		
		Element actionroot = root.getChild("action-mapping");
		List<Element> actio = actionroot.getChildren();
		for(Element e:actio)
		{
			XmlBean action = new XmlBean();
			String name = e.getAttributeValue("name");
			action.setBeanName(name);
			Element actionForm = root.getChild("form-beans");
			List<Element> form = actionForm.getChildren();
			for(Element ex:form){
				if(name.equals(ex.getAttributeValue("name")))
				{
					String formclass = ex.getAttributeValue("class");
					action.setFormClass(formclass);
					break;
				}
			}
			String path = e.getAttributeValue("path");
			action.setPath(path);
			String type = e.getAttributeValue("type");
			action.setActionClass(type);
			
			List<Element> forward = e.getChildren();
			Map<String,String> fmap = new HashMap<String,String>();
			for(Element x:forward)
			{
				String fname = x.getAttributeValue("name");
				String fvalue = x.getAttributeValue("value");
				fmap.put(fname, fvalue);
			}
			action.setActionForward(fmap);
			rmap.put(path, action);
		}
		return rmap;
	}
}
